var app = angular.module('breadTrip', []);
// 解决jinja2和angular的花括号{{}}冲突的方法
app.config(['$interpolateProvider', function($interpolateProvider) {
    $interpolateProvider.startSymbol('{[');
    $interpolateProvider.endSymbol(']}');
}]);
app.controller('orderController', ['$scope', function($scope){
    var localData = getLocalStorage();
    obj.need_invoice = false;
    // 获取数据
    if(localData){
        _array_filter = ['contact_email', 'contact_mobile', 'need_invoice', 'rooms', 'invoice_title', 'preferences', 'customer_preferences'];
        _array_filter.filter(function(i){
            if(i == 'rooms'){
                obj.rooms.filter(function(r, j){
                    for(var o in r){
                        if(o == 'lastName' || o == "firstName" || o == "bedTypeId"){
                            if(localData.rooms && localData.rooms[j]) r[o] = localData.rooms[j][o];
                        }
                    }
                });
            }else{
                obj[i] = localData[i];
            }
        });
    }else{
        // 获取用户信息（默认填写）
        var user_info = JSON.parse(localStorage.getItem('device_' + BT.context('deviceId')));
        if(obj.contact_email == '' || obj.contact_mobile == ''){
            if(user_info){
                obj.contact_mobile = user_info.contact_mobile;
                obj.contact_email = user_info.contact_email;
                obj.rooms.filter(function(i, j){
                    var user_info_room = user_info.rooms[j];
                    if(user_info_room){
                        i.lastName = user_info_room.lastName;
                        i.firstName = user_info_room.firstName;
                    }
                });
            }
        }
    }
    $scope.data = obj;

    function setLocalStorage(){
        if($scope.data && $scope.data.hotel_id){
            if($('.textarea')){
                $scope.data.invoice_title = $('.textarea').text();
                $('.textarea').text($scope.data.invoice_title);
                $scope.data.rooms.filter(function(i, k){
                    i.bedTypeId = $($('input[name="bedTypeId"]')[k]).val();
                });
            }
            localStorage['hotel_' + BT.context('hotelId') +'_order'] = JSON.stringify($scope.data);
        }
    };
    // 从 localStorage 中取出 form 表单数据
    function getLocalStorage(){
        if(BT.context('hotelId')){
            var storageObj = JSON.parse(localStorage.getItem('hotel_' + BT.context('hotelId') +'_order'));
            return storageObj;
        }
    };

    $scope.replace = function(str){
       return str.split('；');
    };

    // 改变房间数量
    $scope.changeRoom = function(n){
        var _url = location.origin + '/hotel/book/search/'+ $scope.data.hotel_id +'?checkin_date=' + BT.context('checkinDate') + '&checkout_date=' + BT.context('checkoutDate') + '&rooms_count=' + n + '&product_id=' + $scope.data.product_id;

        $.ajax({
            url: _url,
            type: "GET",
            success: function(resp) {
                // var res = JSON.parse(resp);
                var res = resp;
                for(var i in res){
                   var _array_filter = ['contact_email', 'contact_mobile', 'need_invoice', 'rooms', 'invoice_title', 'preferences', 'customer_preferences'];
                    _array_filter.filter(function(j, k){
                        if(j == 'rooms'){
                            for(var x in res.rooms){
                                if($scope.data.rooms[x]) res.rooms[x] = $scope.data.rooms[x];
                            }
                        }else{
                            res[j] = $scope.data[j];
                        }
                    });
                }
                $scope.data = res;
                resetData();
                $scope.$apply(); //强制通知

                $.each($('option'), function(i, j){
                    var $j = $(j);
                    if(!$j.attr('label')){
                        $j.remove();
                    }
                });
            },
            error: function(resp) {
                // alert('对不起，请求失败！')
            }
        });
    };

    // function scroll(scrollTo, time) {
    //     var scrollFrom = parseInt(document.body.scrollTop),
    //         i = 0,
    //         runEvery = 5; // run every 5ms

    //     scrollTo = parseInt(scrollTo);
    //     time /= runEvery;

    //     var interval = setInterval(function () {
    //         i++;

    //         document.body.scrollTop = (scrollTo - scrollFrom) / time * i + scrollFrom;

    //         if (i >= time) {
    //             clearInterval(interval);
    //         }
    //     }, runEvery);
    // };

    $scope.submitForm = function(isValid){
        var $btn = $('#submit-btn');
        if($btn.hasClass('disabled')) return;
        if($btn.hasClass('push')) return;
        $btn.addClass('push');
        setLocalStorage();
        var baseData = {'rooms': $scope.data.rooms, 'contact_email': $scope.data.contact_email, 'contact_mobile': $scope.data.contact_mobile};
        localStorage['device_' + BT.context('deviceId')] = JSON.stringify(baseData);
        $scope.valid = true;
        if(isValid){
            //参数重组
            var arr_1 = $('form').serializeArray(), arr_2=[];
            arr_1.filter(function(i, k){
                if(i.name.match(/firstName/) || i.name.match(/lastName/)|| i.name.match(/bedTypeId/) || i.name.match(/adultNum/) || i.name.match(/childAges/)){
                }else{
                    if(i.name) arr_2.push(i);
                }
            });
            var data = $.param(arr_2);
            data = data + '&rooms=' + JSON.stringify($scope.data.rooms);
            var url = location.origin + location.pathname;
            $.ajax({
                url: url,
                type: "POST",
                data: data,
                success: function(resp) {
                    // var info = JSON.parse(resp);
                    var info = resp;
                    if(info){
                        if(info.code == 0){
                            localStorage.removeItem('hotel_' + BT.context('hotelId') +'_order');
                            if($scope.data.mode == 1){
                                // 返回行程
                                vAppSchema.onClickOrderComplete(info.data.order_id);
                            }else{
                                // 去支付页面(缺少id)
                                location.href = location.origin + '/pay/order/' + info.data.order_id;
                            }
                        }else{
                            var tips = [{'checkin_date': '入住时间有误'},
                                {'checkout_date': '退房时间有误'},
                                {'rooms_count': '房间数量有误'},
                                {'room_type': '房型有误'},
                                {'firstName': '护照英文名有误'},
                                {'lastName': '护照英文姓有误'},
                                {'customer_preferences': '住客偏好有误'},
                                {'contact_email': '邮箱有误'},
                                {'contact_mobile': '手机号有误'}
                                 ];
                            tips.filter(function(i,k){
                                for( var key in i){
                                    if(info.message.match(key)) {
                                        info.message = info.message.replace(key, i[key]);
                                        break;
                                    }
                                }
                            });
                            $('.text-error').removeClass('hide').text('提示：' + info.message);
                            window.scrollTo(0,document.body.scrollHeight);
                        }
                        setTimeout(function(){
                            $btn.removeClass('push');
                        }, 100);
                    }
                },
                error: function(resp) {
                    $btn.removeClass('push');
                    $('.text-error').removeClass('hide').text('对不起，服务器异常，请重试！');
                    window.scrollTo(0,document.body.scrollHeight);
                }
            });
        }else{
            $btn.removeClass('push');
            return false;
        }
    };

    $scope.goDetail = function(name, id){
        var $btn = $('#detail-btn');
        if($btn.hasClass('push')) return;
        $btn.addClass('push');
        if($('body').data('version') != 'None'){
            vAppSchema.goPoiDetail(name, id, true, '', id);
        }else{
            location.href = location.origin + '/hotel/product/list/'+ BT.context('hotelId') + '/'+ location.search;
        }
        setTimeout(function(){
            $btn.removeClass('push');
        }, 1000);
    };

    $scope.onKeyDown = function(e){
        if(e.which == 13){
            e.preventDefault();
            return false;
        }
    };

    $scope.focus = function(e){
        // var ua = navigator.userAgent.toLocaleLowerCase();
        // if(ua.match(/iphone/) && ua.match(/mobile/)){
            $('.hotel-bottom').addClass('bottom');
        // }
    };

    $scope.blur = function(e){
        // var ua = navigator.userAgent.toLocaleLowerCase();
        // if(ua.match(/iphone/) && ua.match(/mobile/)){
            $('.hotel-bottom').removeClass('bottom');
        // }
    };

    $scope.confirmEvent = function(){
        $('body').off('touchmove');
        $('.popup').addClass('hide');
    };

    $scope.checkPolicy = function(){
        var $dom = $('.popup.policy');
        $dom.removeClass('hide');
        // 浮层样式设置
        var windowHeight = window.screen.availHeight;
        var $inner = $('#popup-comfirm.policy').find('.popup-inner');
        $inner.css('top', (windowHeight - $inner.height()) / 2);
        $dom.find('.popup-mask').on('click', function(){
            $dom.addClass('hide');
        });
    };

    // 跳转链接
    $scope.goHref = function(type){
        setLocalStorage();
        var url = location.origin + location.pathname;
        if(type.match('date')){
            url = url  + 'date/?type='+type+'&';
        }
        if(type == 'type'){
            url = url + 'product/?';
        }
        if(type == 'preference'){
            url = url + 'preference/?';
        }

        var params = location.search.replace(/\?/,'').split('&'),
            new_array = [];
        for(var i in params){
            var item = params[i].split('=');
            if(item[0] == 'rooms_count' || item[0] == 'product_id' || item[0] == 'checkin_date' || item[0] == 'checkout_date'){

            }else{
                new_array.push(params[i]);
            }
        }
        new_array.push('rooms_count='+$scope.data.rooms_count);
        new_array.push('product_id='+$scope.data.product_id);
        new_array.push('checkin_date='+$scope.data.checkin_date);
        new_array.push('checkout_date='+$scope.data.checkout_date);
        location.href = url + new_array.join('&');
    }

    // 价格显示格式处理
    function price_format(number){
        var n = 0;
        if(number.toString().split('.')[1]) n = 2;
        return n;
    }

    //  数字array
    $scope.getNumberArray= function(num){
        var arr = [];
        if(num > 0){
            for(var i = 1; i <= num; i++){
                arr.push(i);
            }
        }
        return arr;
    };

    function getDays(date_1, date_2){
        return Math.abs(moment(date_1).diff(date_2, "days"));
    }

    function resetData(){
        var days = Math.abs(getDays($scope.data.checkin_date, $scope.data.checkout_date)),
            tax_and_fee = parseFloat($scope.data.taxes_and_fees/days) || 0
            price = (parseFloat($scope.data.average_price)+ tax_and_fee)|| 0,
            total_price  = parseFloat(price * $scope.data.rooms_count * days) || 0;
        $scope.tax_and_fee = tax_and_fee.toFixed(price_format(tax_and_fee));
        $scope.price = price.toFixed(price_format(price));
        $scope.total_price = total_price.toFixed(price_format(total_price));
        var prefer_array = [{0: '无'}, {1: '尽量安排高楼层'},{2: '尽量安排吸烟房'},{3: '尽量安排无烟房'}],
            prefer_ids = ($scope.data.customer_preferences || '0').split(','),
            prefer_text = [];

        if(prefer_ids.length > 1){
            var prefer_ids = prefer_ids.filter(function(i){
                return i!= 0;
            });
        }

        for(var i in prefer_ids){
            prefer_array.filter(function(v, k){
                if(prefer_ids[i] == k) prefer_text.push(v[k]);
            });
        }

        $scope.data.preferences = prefer_text.join(',');
        $scope.data.mode = BT.context('mode');
    }

    $scope.init = function(){
        $scope.$watch('data', function(){
        }, true);
        resetData();
    };
    $scope.init();
}]);
